package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.UserResponseVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.inteceptor.LoginUserInteceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private ProductFeignService productFeignService;

    @Resource
    private OrderItemService orderItemService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页需要用到的数据
     * feign在远程调用之前要构造请求，调用很多的拦截器
     * 存在的问题:
     * 1.feign远程调用会丢失请求头
     *      浏览器发送请求头自动带了cookie -> order服务 -> 远程调用，创建一个新的request，没有任何请求头【必须加上feign远程调用的请求拦截器，将老请求中Cookie等请求头同步到新请求】 -> cart服务，没有请求头，购物车服务认为没登录
     * 2.异步情况下， feign丢失请求上下文
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        // 获取用户
        UserResponseVo userResponseVo = LoginUserInteceptor.loginUser.get();
        // 业务
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        // 异步任务执行之前，先共享数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // 在主线程中拿到原来的数据，在父线程里面共享RequestContextHolder
            // 只有共享，拦截其中才会有数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 1.远程查询所有的收获地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(userResponseVo.getId());
            orderConfirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            // 在主线程中拿到原来的数据，在父线程里面共享RequestContextHolder
            // 只有共享，拦截其中才会有数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 2.远程查询购物车选中的购物项
            List<OrderItemVo> orderItemVos = cartFeignService.currentCartItems();
            orderConfirmVo.setItems(orderItemVos);
        }, executor).thenRunAsync(()-> {
            List<OrderItemVo> items = orderConfirmVo.getItems();
            // 批量查询所有商品的库存信息
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wmsFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> data = r.getData(new TypeReference<List<SkuHasStockVo>>(){});
            if (!CollectionUtils.isEmpty(data)) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        }, executor);

        // 3.查询用户积分
        Integer integration = userResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        // 防重令牌
        String uuid = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(uuid);
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + userResponseVo.getId(), uuid, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        // 返回数据
        return orderConfirmVo;
    }

    /**
     * 下单
     * @param orderSubmitVo
     * @return
     */
    // 本地事务，在分布式系统下，只能控制住自己的回滚，控制不了其他服务的回滚
    // 同一对象内事务方法互调默认失效，原因，绕过了代理对象
    // 需要使用分布式事务，最大问题就是，网络问题
    @Override
    @Transactional
//    @GlobalTransactional
    public SubmitOrderRespVo submitOrder(OrderSubmitVo orderSubmitVo) {
        SubmitOrderRespVo submitOrderRespVo = new SubmitOrderRespVo();
        submitOrderRespVo.setCode(0);
        // 创建订单，验令牌，验价格，锁库存
        // 1.验证令牌【令牌的对比和删除必须保证原子性】
        // 脚本返回的是 0-失败 和 1-成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        UserResponseVo userResponseVo = LoginUserInteceptor.loginUser.get();

        confirmVoThreadLocal.set(orderSubmitVo);
        /*
         * redis lur脚本命令解析
         * if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end
         *  1、redis调用get方法来获取一个key的值，如果这个get出来的值等于我们传过来的值
         *  2、然后就执行删除，根据这个key进行删除，删除成功返回1，验证失败返回0
         *  3、删除否则就是0
         *  总结：相同的进行删除，不相同的返回0
         * 脚本大致意思
         */
        // 原子验证和删除
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + userResponseVo.getId()),
                orderToken);
        if (result == 0L) {
            submitOrderRespVo.setCode(1);   // 重复提交
            return submitOrderRespVo;
        } else {
            // 创建订单
            OrderCreateTo order = this.createOrder();
            // 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 金额对比成功
                // 保存订单
                this.saveOrder(order);
                // 库存锁定，只要有异常回滚订单数据
                // 订单号，所有订单项（skuId, skuName）
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVoList = order.getOrderItems().stream().map(orderItem -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(orderItem.getSkuId());
                    orderItemVo.setCount(orderItem.getSkuQuantity());
                    orderItemVo.setTitle(orderItem.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVoList);
                // 远程锁库存
                // 为了保证高并发，库存服务自己回滚，可以发消息给库存服务
                // 库存服务本身也可以使用自动解锁模式 消息
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    // 锁成功了
                    submitOrderRespVo.setOrderEntity(order.getOrder());
                    // TODO 远程扣减积分
                    // TODO 订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return submitOrderRespVo;
                } else {
                    // 锁定失败
                    throw new NoStockException(null);
//                    submitOrderRespVo.setCode(3);
//                    return submitOrderRespVo;
                }
            } else {
                submitOrderRespVo.setCode(2);   // 金额验价失败
                return submitOrderRespVo;
            }
        }
    }

    /**
     * 根据订单号获取订单信息
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    /**
     * 关闭订单
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            // 关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            // 发给mq
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                // TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                // TODO 定期扫描，将未发送的消息重新发送
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                // TODO 出现问题，可以将没法送成功的消息，进行重试发送
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
    }

    /**
     * 根据订单号获取支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setTotal_amount(order.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());    // 保留两位小数，向上取值
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject(orderItemEntities.get(0).getSkuName());
        payVo.setBody(orderItemEntities.get(0).getSkuAttrsVals());
        return payVo;
    }

    /**
     * 保存订单数据
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        // 订单
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        this.baseMapper.insert(order);
        // 订单项
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();

        // 1.创建订单信息
        OrderEntity orderEntity = this.buildOrder(orderSn);
        orderCreateTo.setOrder(orderEntity);
        // 2.获取订单项信息
        List<OrderItemEntity> orderItemEntities = this.buildOrderItems(orderSn);
        orderCreateTo.setOrderItems(orderItemEntities);
        // 3.计算价格、积分等相关信息
        this.computePrice(orderEntity, orderItemEntities);

        orderCreateTo.setOrder(orderEntity);

        return orderCreateTo;
    }

    /**
     * 计算价格相关
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        // 订单总额
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            total = total.add(orderItemEntity.getRealAmount());
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(orderItemEntity.getGiftGrowth()));
        }
        orderEntity.setTotalAmount(total);
        // 应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        // 设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());

        orderEntity.setDeleteStatus(0); // 删除状态
    }

    /**
     * 构建订单
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        // 订单号
        orderEntity.setOrderSn(orderSn);
        // 会员id
        orderEntity.setUserId(LoginUserInteceptor.loginUser.get().getId());
        // 远程获取收货地址信息
        R r = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {});
        BigDecimal fare = fareVo.getFare();
        orderEntity.setFreightAmount(fare); // 运费
        orderEntity.setReceiverCity(fareVo.getMemberAddressVo().getCity()); // 收货人信息
        orderEntity.setReceiverAddress(fareVo.getMemberAddressVo().getAddress());
        orderEntity.setReceiverName(fareVo.getMemberAddressVo().getName());
        orderEntity.setReceiverPhone(fareVo.getMemberAddressVo().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getMemberAddressVo().getPostCode());
        orderEntity.setReceiverProvince(fareVo.getMemberAddressVo().getProvince());
        orderEntity.setReceiverRegion(fareVo.getMemberAddressVo().getRegion());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());    // 订单状态信息
        orderEntity.setAutoConfirmDay(7);   // 订单自动确认时间，默认7天
        return orderEntity;
    }

    /**
     * 构建订单项数据
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每个购物项的价格
        List<OrderItemVo> orderItemVos = cartFeignService.currentCartItems();
        if (!CollectionUtils.isEmpty(orderItemVos)) {
            List<OrderItemEntity> orderItemEntities = orderItemVos.stream().map(orderItemVo -> {
                OrderItemEntity orderItemEntity = this.buildOrderItem(orderItemVo);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return orderItemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     * @param orderItemVo
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1.订单信息
        // 2.商品的spu信息
        Long skuId = orderItemVo.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        // 3.商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPic(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.join(orderItemVo.getSkuAttr(), ","));
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        // 4.优惠信息 忽略
        // 5.积分信息
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())).intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())).intValue());
        // 6.订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        BigDecimal original = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal real = original.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(real);    // 当前订单项的实际金额

        return orderItemEntity;
    }

}